﻿from django.http import HttpResponse, HttpResponseRedirect
from django.core.paginator import ObjectPaginator, InvalidPage
from app.forum import models
from app.engine import models as models1
from google.appengine.api import users
from google.appengine.ext import db
from datetime import datetime
from app.functions.funcs import render,split_tags,formate_time,gen_duration,gen_quote
from app.base.auth import LoginUrl,ChkAuth,admin_required,login_required,member_required
from app.functions.postmarkup import render_bbcode
from google.appengine.api import memcache
from google.appengine.api import images

def index(request, page=1):
    user = users.get_current_user()
    greeting = LoginUrl()
    multi_language = memcache.get_multi(['fa_forum_menu_home','fa_forum_menu_dkp','fa_forum_menu_help','fa_forum_menu_admin',
                                        'fa_forum_second_menu_topic','fa_forum_second_menu_setting',
                                        'fa_forum_index_lang_title',
                                        'fa_forum_index_lang_author',
                                        'fa_forum_index_lang_reply',
                                        'fa_forum_index_lang_latest_reply',
                                        'fa_forum_pagin_lang_next',
                                        'fa_forum_pagin_lang_prev',
                                        'fa_forum_sider_lang_home',
                                        'fa_forum_sider_lang_register',
                                        'fa_forum_sider_lang_create_topic',
                                        'fa_forum_sider_lang_member_info',
                                        'fa_forum_sider_lang_signout',
                                        'fa_forum_sider_lang_signin'])
    try:
        page = int(page)-1
    except:
        page = 0
    show_prev = False
    show_next = False
    topics = models.Topic.all().order('-queue')
    paginator = ObjectPaginator(topics, 15)
    if page >= paginator.pages:
        page = paginator.pages - 1
    topics=paginator.get_page(page)
    pages=range(1,paginator.pages+1)
    show_prev = paginator.has_previous_page(page)
    show_next = paginator.has_next_page(page)
    page=page+1
    payload = dict(show_prev=show_prev,
                   show_next=show_next,
                   page=page,
                   pages=pages,
                   prev=page-1,
                   next=page+1,
                   topics=topics,
                   multi_language=multi_language,
                   page_type='forum',
                   user=user,
                   greeting=greeting,
                   quotation=viewquote())
    return render('forum.html',payload)

@login_required
def Register(request):
    multi_language = memcache.get_multi(['fa_forum_menu_home','fa_forum_menu_dkp','fa_forum_menu_help','fa_forum_menu_admin','fa_forum_memberinfo_lang_username',
                                        'fa_forum_second_menu_topic','fa_forum_second_menu_setting',
                                        'fa_forum_memberinfo_lang_homepage',
                                        'fa_forum_memberinfo_lang_email',
                                        'fa_forum_memberinfo_lang_gender',
                                        'fa_forum_memberinfo_lang_summary',
                                        'fa_forum_memberinfo_lang_player',
                                        'fa_forum_memberinfo_lang_submit',
                                        'fa_forum_pagin_lang_next',
                                        'fa_forum_pagin_lang_prev',
                                        'fa_forum_sider_lang_home',
                                        'fa_forum_sider_lang_register',
                                        'fa_forum_sider_lang_create_topic',
                                        'fa_forum_sider_lang_member_info',
                                        'fa_forum_sider_lang_signout',
                                        'fa_forum_sider_lang_signin'])
    user = users.get_current_user()
    try:
        member = models.Members.all().filter('user =', user)
        if member.count() > 0:
            return HttpResponseRedirect('/forum/members/info/')
    except:
        pass
    greeting = LoginUrl()
    user = users.get_current_user()
    if request.method == 'POST':
        try:
            player = request.POST.get('player').decode('utf-8')
            player = models1.Players.all().filter('player_name =',player).fetch(1)
            player = player[0].key()
        except:
            player = None
        for f,file_info in request.FILES.items():
            avaster = file_info['content']
        username = request.POST.get('username').decode('utf-8')
        gender = request.POST.get('gender')
        summary = request.POST.get('summary').decode('utf-8')
        email = request.POST.get('email')
        homepage = request.POST.get('homepage')

        member_obj = models.Members(username=username,
                                    gender=gender,
                                    summary=summary,
                                    email=email,
                                    player=player,
                                    homepage=homepage,
                                    multi_language=multi_language,
                                    page_type='forum',
                                    avaster = avaster)
        member_obj.put()
        return HttpResponseRedirect('/forum/members/info/')
    payload = dict(quotation=viewquote(),greet=greeting,page_type='forum',multi_language=multi_language,user=user)
    return render('userform.html', payload)

@member_required
def MemberInfo(request):
    multi_language = memcache.get_multi(['fa_forum_menu_home','fa_forum_menu_dkp','fa_forum_menu_help','fa_forum_menu_admin','fa_forum_memberinfo_lang_username',
                                        'fa_forum_second_menu_topic','fa_forum_second_menu_setting',
                                        'fa_forum_memberinfo_lang_homepage',
                                        'fa_forum_memberinfo_lang_email',
                                        'fa_forum_memberinfo_lang_gender',
                                        'fa_forum_memberinfo_lang_summary',
                                        'fa_forum_memberinfo_lang_player',
                                        'fa_forum_memberinfo_lang_submit',
                                        'fa_forum_sider_lang_home',
                                        'fa_forum_sider_lang_register',
                                        'fa_forum_sider_lang_create_topic',
                                        'fa_forum_sider_lang_member_info',
                                        'ca_human','ca_dwraf','ca_nightelf','ca_gnome','ca_draenei',
                                        'ca_troll','ca_undead','ca_tauren','ca_bloodelf','ca_orc',
                                        'ca_warrior','ca_paladin','ca_priest','ca_rogue','ca_mage','ca_warlock','ca_druid','ca_hunter','ca_shaman','ca_deathknight',
                                        'fa_forum_sider_lang_signout',
                                        'fa_forum_sider_lang_signin'])
    greeting = LoginUrl()
    user = users.get_current_user()
    member = models.Members.all().filter('user =',user).fetch(1)
    member = member[0]
#    member = models.Members.get_by_id(int(member_id))
    if request.method == 'POST':
        try:
            for f,file_info in request.FILES.items():
                avaster = file_info['content']
            thumbnail = flickr_thumb(avaster,48)
            member.avaster = avaster
            member.thumbnail = thumbnail
        except:
            pass
        member.username = request.POST.get('username').decode('utf-8')
        member.gender = request.POST.get('gender')
        try:
            player = request.POST.get('player').decode('utf-8')
            player = models1.Players.all().filter('player_name =',player).fetch(1)
            player = player[0].key()
            member.player = player
        except:
            member.player = None
        member.summary = request.POST.get('summary').decode('utf-8')
        member.email = request.POST.get('email')
        member.homepage = request.POST.get('homepage')
        member.put()
    payload = dict(quotation=viewquote(),member=member,greet=greeting,multi_language=multi_language,page_type='forum',user=user)
    return render('userform.html', payload)

@member_required
def CreateTopic(request):
    multi_language = memcache.get_multi(['fa_forum_menu_home','fa_forum_menu_dkp','fa_forum_menu_help','fa_forum_menu_admin','fa_forum_createtopic_lang_topic_title',
                                        'fa_forum_second_menu_topic','fa_forum_second_menu_setting',
                                        'fa_forum_createtopic_lang_topic_content',
                                        'fa_forum_createtopic_lang_submit',
                                        'fa_forum_sider_lang_home',
                                        'fa_forum_sider_lang_register',
                                        'fa_forum_sider_lang_create_topic',
                                        'fa_forum_sider_lang_member_info',
                                        'fa_forum_sider_lang_signout',
                                        'fa_forum_sider_lang_signin'])
    greeting = LoginUrl()
    user = users.get_current_user()
    if request.method == 'POST':
        title = request.POST.get('title').decode('utf-8')
        author = models.Members.all().filter('user =', user)
        author = author[0]
        content = request.POST.get('content').decode('utf-8')
        topic = models.Topic(title=title,author=author,content=content)
        topic.post_topic()
        return HttpResponseRedirect('/forum/topic/view/%s' %topic.key().id())
    payload = dict(quotation=viewquote(),greeting=greeting,multi_language=multi_language,page_type='forum',user=user)
    return render('CreateTopic.html',payload)

@member_required
def EditTopic(request,topic_id):
    multi_language = memcache.get_multi(['fa_forum_menu_home','fa_forum_menu_dkp','fa_forum_menu_help','fa_forum_menu_admin','fa_forum_createtopic_lang_topic_title',
                                        'fa_forum_second_menu_topic','fa_forum_second_menu_setting',
                                        'fa_forum_createtopic_lang_topic_content',
                                        'fa_forum_createtopic_lang_submit',
                                        'fa_forum_sider_lang_home',
                                        'fa_forum_sider_lang_register',
                                        'fa_forum_sider_lang_create_topic',
                                        'fa_forum_sider_lang_member_info',
                                        'fa_forum_sider_lang_signout',
                                        'fa_forum_sider_lang_signin'])
    greeting = LoginUrl()
    user = users.get_current_user()
    topic = models.Topic.get_by_id(int(topic_id))
    if request.method == 'POST':
        topic.title = request.POST.get('title').decode('utf-8')
        topic.content = request.POST.get('content').decode('utf-8')
        topic.put()
        return HttpResponseRedirect('/forum/topic/view/%s' %topic.key().id())
    payload = dict(quotation=viewquote(),greeting=greeting,topic=topic,multi_language=multi_language,page_type='forum',user=user)
    return render('CreateTopic.html',payload)

def ViewTopic(request, topic_id):
    multi_language = memcache.get_multi(['fa_forum_menu_home','fa_forum_menu_dkp','fa_forum_menu_help','fa_forum_menu_admin','fa_forum_view_lang_delete',
                                        'fa_forum_second_menu_topic','fa_forum_second_menu_setting',
                                        'fa_forum_view_lang_edit',
                                        'fa_forum_view_lang_by',
                                        'fa_forum_view_lang_from',
                                        'fa_forum_view_lang_submit',
                                        'fa_forum_sider_lang_home',
                                        'fa_forum_sider_lang_register',
                                        'fa_forum_sider_lang_create_topic',
                                        'fa_forum_sider_lang_member_info',
                                        'fa_forum_sider_lang_signout',
                                        'fa_forum_sider_lang_signin'])
    greeting = LoginUrl()
    user = users.get_current_user()
    topic = models.Topic.get_by_id(int(topic_id))
    topic_content = render_bbcode(topic.content, "UTF-8")
    replies = []
    for reply in models.Reply.all().filter("topic =", topic).order("post_on"):
        reply.content = render_bbcode(reply.content, "UTF-8")
        replies.append(reply)
    try:
        author = models.Members.all().filter('user =', user).fetch(1)
        author = author[0]
        if request.method == 'POST':
            content = request.POST.get('content').decode('utf-8')
            reply = models.Reply(content=content,author=author,topic=topic.key())
            reply.put_reply()
            return HttpResponseRedirect('/forum/topic/view/%s' %topic.key().id())
    except:
        author = None
    payload = dict(quotation=viewquote(),greeting=greeting,topic=topic,replies=replies,user=user,author=author,topic_content=topic_content,multi_language=multi_language,page_type='forum')
    return render('viewTopic.html', payload)

def DelTopic(request, topic_id):
    topic = models.Topic.get_by_id(int(topic_id))
    user = users.get_current_user()
    if user == topic.author.user:
        topic.delete()
    else:
        pass
    return HttpResponseRedirect('/forum/topic/')

def DelReply(request, reply_id):
    reply = models.Reply.get_by_id(int(reply_id))
    user = users.get_current_user()
    if user == reply.author.user:
        reply.delete()
    else:
        pass
    return HttpResponseRedirect('/forum/topic/view/%s' %reply.topic.key().id())

def helpme(request):
    user = users.get_current_user()
    greeting = LoginUrl()
    multi_language = memcache.get_multi(['fa_forum_menu_home','fa_forum_menu_dkp','fa_forum_menu_help','fa_forum_menu_admin','fa_forum_sider_lang_home',
                                        'fa_forum_second_menu_fhelp','fa_forum_second_menu_dhelp',
                                        'fa_forum_sider_lang_register',
                                        'fa_forum_sider_lang_create_topic',
                                        'fa_forum_sider_lang_member_info',
                                        'fa_forum_sider_lang_signout',
                                        'fa_forum_sider_lang_signin'])
    payload=dict(quotation=viewquote(),user=user,page_type='help',multi_language=multi_language)
    return render('help.html', payload)

def getavaster(request,member_id):
    member = models.Members.get_by_id(int(member_id))
    avaster=HttpResponse(member.avaster,mimetype='image/png')
    return avaster

def getthumbnail(request,member_id):
    member = models.Members.get_by_id(int(member_id))
    thumbnail=HttpResponse(member.thumbnail,mimetype='image/png')
    return thumbnail

def genthumbnail(img_data,dx):
    dx = int(dx)
    try:
        img = images.Image(img_data)
        # Basically, we just want to make sure it's a PNG
        # since we don't have a good way to determine image type
        # through the API, but the API throws an exception
        # if you don't do any transforms, so go ahead and use im_feeling_lucky.
        img.im_feeling_lucky()
        avaster_data = img.execute_transforms(images.PNG)
        img.resize(dx, dx)
        thumbnail_data = img.execute_transforms(images.PNG)
    except:
        pass
    return thumbnail_data

def flickr_thumb(file,size):
    size = int(size)
    img = images.Image(file)
    img.im_feeling_lucky()
    if img.width > img.height:
        img.crop(.0,.0,float(img.height)/float(img.width),1.0)
    else:
        img.crop(.0,.0,1.0,float(img.width)/float(img.height))
    img.resize(size)
    return img.execute_transforms(images.PNG)

@member_required
def profile(request,username):
    greeting = LoginUrl()
    user = users.get_current_user()
    profile = models.Members.all().filter('username =', username).fetch(1)
    profile = profile[0]
    topics = models.Topic.all().filter('author =',profile.user).fetch(5)
    replies = models.Reply.all().filter('author =',profile.key()).fetch(5)
    twitters = models.Twitters.all().order('post_on').fetch(10)
    if request.method == 'POST':
        twitter = request.POST.get('twitter').decode('utf-8')
        twitter = models.Twitters(twitter=twitter,author=profile.key())
        twitter.put()
        return HttpResponseRedirect('/people/%s' %profile.username)
    multi_language = memcache.get_multi(['fa_forum_menu_home','fa_forum_menu_dkp','fa_forum_menu_help','fa_forum_menu_admin','fa_forum_sider_lang_home',
                                        'fa_forum_second_menu_fhelp','fa_forum_second_menu_dhelp',
                                        'fa_forum_sider_lang_register',
                                        'fa_forum_sider_lang_create_topic',
                                        'fa_forum_sider_lang_member_info',
                                        'fa_forum_sider_lang_signout',
                                        'fa_forum_sider_lang_signin'])
    payload=dict(quotation=viewquote(),twitters=twitters,topics=topics,replies=replies,profile=profile,user=user,page_type='forum',multi_language=multi_language)
    return render('people.html', payload)


@member_required
def CreateQuote(request):
    multi_language = memcache.get_multi(['fa_forum_menu_home','fa_forum_menu_dkp','fa_forum_menu_help','fa_forum_menu_admin','fa_forum_view_lang_delete',
                                    'fa_forum_second_menu_topic','fa_forum_second_menu_setting',
                                    'fa_forum_view_lang_edit',
                                    'fa_forum_view_lang_by',
                                    'fa_forum_view_lang_from',
                                    'fa_forum_view_lang_submit',
                                    'fa_forum_sider_lang_home',
                                    'fa_forum_sider_lang_register',
                                    'fa_forum_sider_lang_create_topic',
                                    'fa_forum_sider_lang_member_info',
                                    'fa_forum_sider_lang_signout',
                                    'fa_forum_sider_lang_signin'])
    greeting = LoginUrl()
    user = users.get_current_user()
    author = models.Members.all().filter('user =', user).fetch(1)
    author = author[0]
    quotations = models.Quotations.all()
    if request.method == 'POST':
        quote = request.POST.get('quotation').decode('utf-8')
        quotation = models.Quotations(quotation=quote,author=author)
        quotation.put()
        return HttpResponseRedirect('/quote/')
    payload = dict(quotation=viewquote(),quotations=quotations,user=user,page_type='forum',multi_language=multi_language)
    return render('quote.html', payload)


def viewquote():
    quotations = models.Quotations.all()
    num = quotations.count()
    quotation = quotations.fetch(1,gen_quote(num))
    quotation = quotation[0].quotation
    return quotation

@member_required
def sendMail(request,member_id):
    multi_language = memcache.get_multi(['fa_forum_menu_home','fa_forum_menu_dkp','fa_forum_menu_help','fa_forum_menu_admin','fa_forum_view_lang_delete',
                                        'fa_forum_second_menu_topic','fa_forum_second_menu_setting',
                                        'fa_forum_view_lang_edit',
                                        'fa_forum_view_lang_by',
                                        'fa_forum_view_lang_from',
                                        'fa_forum_view_lang_submit',
                                        'fa_forum_sider_lang_home',
                                        'fa_forum_sider_lang_register',
                                        'fa_forum_sider_lang_create_topic',
                                        'fa_forum_sider_lang_member_info',
                                        'fa_forum_sider_lang_signout',
                                        'fa_forum_sider_lang_signin'])
    greeting = LoginUrl()
    user = users.get_current_user()

    if request.method == 'POST':
        content = request.POST.get('content').decode('utf-8')
        title = request.POST.get('title').decode('utf-8')
        theuser= models.Members.all().filter('user =', user).fetch(1)
        from_user = theuser[0].key()
        to_user = models.Members.get_by_id(int(member_id)).key()
        imail = models.iMail(title=title,content=content,from_user=from_user,to_user=to_user)
        imail.put()
        return HttpResponseRedirect('/imail/sendmail/%s' %member_id)
    payload = dict(quotation=viewquote(),user=user,page_type='forum',multi_language=multi_language)
    return render('sendmail.html', payload)

@member_required
def getMail(request,page=1):
    multi_language = memcache.get_multi(['fa_forum_menu_home','fa_forum_menu_dkp','fa_forum_menu_help','fa_forum_menu_admin','fa_forum_view_lang_delete',
                                    'fa_forum_second_menu_topic','fa_forum_second_menu_setting',
                                    'fa_forum_view_lang_edit',
                                    'fa_forum_view_lang_by',
                                    'fa_forum_view_lang_from',
                                    'fa_forum_view_lang_submit',
                                    'fa_forum_sider_lang_home',
                                    'fa_forum_sider_lang_register',
                                    'fa_forum_sider_lang_create_topic',
                                    'fa_forum_sider_lang_member_info',
                                    'fa_forum_sider_lang_signout',
                                    'fa_forum_sider_lang_signin'])

    greeting = LoginUrl()
    user = users.get_current_user()
    current_member = models.Members.all().filter('user =', user).fetch(1)
    current_member = current_member[0]
    mails = models.iMail.all().filter('to_user =',current_member)
    try:
        page = int(page)-1
    except:
        page = 0
    show_prev = False
    show_next = False
    paginator = ObjectPaginator(mails, 5)
    if page >= paginator.pages:
        page = paginator.pages - 1
    mails=paginator.get_page(page)
    pages=range(1,paginator.pages+1)
    show_prev = paginator.has_previous_page(page)
    show_next = paginator.has_next_page(page)
    page=page+1
    payload = dict(page=page,
                   show_prev=show_prev,
                   show_next=show_next,
                   pages=pages,
                   prev=page-1,
                   next=page+1,
                   quotation=viewquote(),
                   user=user,
                   page_type='forum',
                   mails=mails,
                   multi_language=multi_language)
    return render('listmail.html', payload)

@member_required
def viewMail(request,mail_id):
    multi_language = memcache.get_multi(['fa_forum_menu_home','fa_forum_menu_dkp','fa_forum_menu_help','fa_forum_menu_admin','fa_forum_view_lang_delete',
                                    'fa_forum_second_menu_topic','fa_forum_second_menu_setting',
                                    'fa_forum_view_lang_edit',
                                    'fa_forum_view_lang_by',
                                    'fa_forum_view_lang_from',
                                    'fa_forum_view_lang_submit',
                                    'fa_forum_sider_lang_home',
                                    'fa_forum_sider_lang_register',
                                    'fa_forum_sider_lang_create_topic',
                                    'fa_forum_sider_lang_member_info',
                                    'fa_forum_sider_lang_signout',
                                    'fa_forum_sider_lang_signin'])
    greeting = LoginUrl()
    user = users.get_current_user()
    imail = models.iMail.get_by_id(int(mail_id))
    payload = dict(imail=imail,quotation=viewquote(),user=user,page_type='forum',multi_language=multi_language)
    return render('viewmail.html', payload)


def forumHelp(request):
    user = users.get_current_user()
    greeting = LoginUrl()
    multi_language = memcache.get_multi(['fa_forum_menu_home','fa_forum_menu_dkp','fa_forum_menu_help','fa_forum_menu_admin','fa_forum_sider_lang_home',
                                        'fa_forum_second_menu_fhelp','fa_forum_second_menu_dhelp',
                                        'fa_forum_sider_lang_register',
                                        'fa_forum_sider_lang_create_topic',
                                        'fa_forum_sider_lang_member_info',
                                        'fa_forum_sider_lang_signout',
                                        'fa_forum_sider_lang_signin'])
    payload=dict(quotation=viewquote(),user=user,page_type='help',multi_language=multi_language)
    return render('forum_help.html', payload)

def dkpHelp(request):
    user = users.get_current_user()
    greeting = LoginUrl()
    multi_language = memcache.get_multi(['fa_forum_menu_home','fa_forum_menu_dkp','fa_forum_menu_help','fa_forum_menu_admin','fa_forum_sider_lang_home',
                                        'fa_forum_second_menu_fhelp','fa_forum_second_menu_dhelp',
                                        'fa_forum_sider_lang_register',
                                        'fa_forum_sider_lang_create_topic',
                                        'fa_forum_sider_lang_member_info',
                                        'fa_forum_sider_lang_signout',
                                        'fa_forum_sider_lang_signin'])
    payload=dict(quotation=viewquote(),user=user,page_type='help',multi_language=multi_language)
    return render('dkp_help.html', payload)


